package cn.tedu.knows.portal.controller;

import cn.tedu.knows.portal.service.IUserService;
import cn.tedu.knows.portal.vo.RegisterVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

@RestController
//lombok提供的注解@Slf4j,能够在当前类中生成一个记录日志的对象
//我们在本类方法中可以使用这个对象记录日志
@Slf4j
public class SystemController {
    @Autowired
    private IUserService userService;

    @PostMapping("/register")
    public String register(@Validated RegisterVO registerVO,
                           //专门接收前面验证的结果用的
                           //我们判断这个result是否有错误信息
                           BindingResult result) {
        //log 对象就是@Slf4j注解生效提供的,它能够记录日志
        log.debug("接收到表单信息:{}", registerVO);
        if (result.hasErrors()) {
            //获得验证结果中的错误信息(多条错误信息随机获取)
            String msg = result.getFieldError().getDefaultMessage();
            return msg;
        }

        userService.registerStudent(registerVO);
        return "ok";
    }

    // 从 application.properties文件中获取配置的信息
    @Value("${knows.resource.path}")
    private File resourcePath;

    @Value("${knows.resource.host}")
    private String resourceHost;

    @PostMapping("/upload/file")
    public String upload(MultipartFile imageFile) throws IOException {
        String path = DateTimeFormatter.ofPattern("yyyy/MM/dd").format(LocalDate.now());
        //实例化要上传的文件夹对象
        //F:/upload/2021/12/03
        File folder = new File(resourcePath, path);
        //创建文件夹
        folder.mkdirs();
        String filename = imageFile.getOriginalFilename();
        String ext = filename.substring(filename.lastIndexOf("."));
        String name = UUID.randomUUID().toString() + ext;
        //确定随机文件名
        File file = new File(folder, name);
        log.debug("文件上传到:{}", file.getAbsoluteFile());
        //执行上传操作
        imageFile.transferTo(file);
        String url = resourceHost + "/" + path + "/" + name;
        log.debug("可显示图片的url:{}", url);
        //返回url,以实现图片的回显
        return url;
    }
}
